//
//  StagesViewController.m
//  MatchTouch
//
//  Created by SUN DONG LEE on 13. 1. 21..
//  Copyright (c) 2013년 SUN DONG LEE. All rights reserved.
//

#import "StagesViewController.h"
#import "QuizViewController.h"
#import "AppDelegate.h"

@interface StagesViewController ()

@end

@implementation StagesViewController
//@synthesize stage_num;

int hScreenWidth;
int hColumns=3;

int hMargin=60;
int hBtnWidth=40;
int hGap;

int hMargin_iPad=90;
int hBtnWidth_iPad=100;
int hGap_iPad;


int vScreenHeight;
int vRows=6;

int vMargin=70;
int vBtnHeight=40;
int vGap;

int vMargin_iPad=100;
int vBtnHeight_iPad=100;
int vGap_iPad;


NSMutableDictionary *buttonDictionary;
NSMutableDictionary *labelDictionary;


- (AppDelegate *)appDelegate {
	return [[UIApplication sharedApplication] delegate];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad...");
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    // 상태바 숨기기
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        // iOS 7
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    } else {
        // iOS 6
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    }
    
    CGSize result = [[UIScreen mainScreen] bounds].size;
    vScreenHeight=result.height;
    hScreenWidth=result.width;
    
    hGap=(hScreenWidth-(hMargin*2)-(hColumns*hBtnWidth))/(hColumns-1);
    vGap=(vScreenHeight-(vMargin*2)-(vRows*vBtnHeight))/(vRows-1);
    
    hGap_iPad=(hScreenWidth-(hMargin_iPad*2)-(hColumns*hBtnWidth_iPad))/(hColumns-1);
    vGap_iPad=(vScreenHeight-(vMargin_iPad*2)-(vRows*vBtnHeight_iPad))/(vRows-1);
    
    [_btn_forSegue setAlpha:0.0];
    
    buttonDictionary = [[NSMutableDictionary alloc] init];
    labelDictionary = [[NSMutableDictionary alloc] init];
    
    [self makeGrid];
    NSLog(@"makeGrid completed...");
}

// 상태바 숨기기
- (BOOL)prefersStatusBarHidden {
    return YES;
}

int stage_seq=1;

- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"viewWillAppear...");
    //TODO:뷰에 자물쇠 그림 붙이기..(스테이지 버튼을 어레이에 모두 넣어두고 관리...)
    stage_seq=1;
    
    [self setLock];
    NSLog(@"setLock completed...");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//TODO: 1번 버튼에서 2번 실행되는 문제..
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"segue_stages_2_quiz"]) {
        QuizViewController *destViewController = segue.destinationViewController;
        destViewController.received_stage_num = _stage_num;
    }
}


- (IBAction)act_stage_button_pressed:(UIButton *)sender {
    _stage_num = [sender.titleLabel.text intValue];
    [self performSegueWithIdentifier:@"segue_stages_2_quiz" sender:self];
}

//문제 버튼을 만듦, 초기화 작업에 해당하므로 버튼 생성 후 여러 초기화 작업을 수행함.
- (void)makeGrid {
    UIImage *image = [UIImage imageNamed:@"ICO_BTN.png"];
    for (int y=0; y<vRows; y++) {
        for (int x=0; x<hColumns; x++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //버튼 생성

            UILabel *label = [[UILabel alloc] init];
            
            [button setTitle:[[NSNumber numberWithInt:stage_seq] stringValue] forState:UIControlStateNormal];
            [button setBackgroundImage:image forState:UIControlStateNormal]; //버튼 백그라운드를 노란색 동그란 버튼 아이콘(ICO_BTN.png)로 설정

            [label setTextAlignment:NSTextAlignmentCenter];
            [buttonDictionary setObject:button forKey:button.titleLabel.text];
            [labelDictionary setObject:label forKey:button.titleLabel.text];
            
            stage_seq++;
            [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; //버튼셀렉터 설정

            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { //iPhone
                button.frame = CGRectMake((hBtnWidth+hGap)*x+hMargin, (vBtnHeight+vGap)*y+vMargin, hBtnWidth, vBtnHeight);
                label.frame = CGRectMake((hBtnWidth+hGap)*x+hMargin, (vBtnHeight+vGap)*y+vMargin+vBtnHeight+2, hBtnWidth, 14);

            } else { //iPad
                //button.frame = CGRectMake(100*x+90, 100*y+170, 90.0, 90.0); //버튼 위치와 크기 설정
                button.frame = CGRectMake((hBtnWidth_iPad+hGap_iPad)*x+hMargin_iPad, (vBtnHeight_iPad+vGap_iPad)*y+vMargin_iPad, hBtnWidth_iPad, vBtnHeight_iPad);
                label.frame = CGRectMake((hBtnWidth_iPad+hGap_iPad)*x+hMargin_iPad, (vBtnHeight_iPad+vGap_iPad)*y+vMargin_iPad+vBtnHeight_iPad+2, hBtnWidth_iPad, 14);

            }

            [[self view] addSubview:button]; //버튼을 뷰에 추가하기
            [[self view] addSubview:label];
        }
    }
}

- (void)buttonClicked:(UIButton*)button
{
    if ([button.titleLabel.text integerValue]<=[self appDelegate].highWaterMark) {
        _stage_num = [button.titleLabel.text intValue];
        [self performSegueWithIdentifier:@"segue_stages_2_quiz" sender:self];
    }
}

NSString *stars;

- (void)setLock {
    UIImage *image = [UIImage imageNamed:@"ICO_GRAY_LOCK.png"];
    for (NSString *key in buttonDictionary) {
        if ([self appDelegate].highWaterMark<[key intValue]) {
            [[buttonDictionary objectForKey:key] setBackgroundImage:image forState:UIControlStateNormal];
            [[buttonDictionary objectForKey:key] setTitle:@"" forState:UIControlStateNormal];
        } else {
            stars=[[self appDelegate].highStars objectForKey:[NSNumber numberWithInt:[key intValue]]];
            if (stars != NULL) {
                [[labelDictionary objectForKey:key] setText:[NSString stringWithFormat:@"%@",stars]];
            }
            
        }
    }
}

@end
